<template>
  <div class="updataSelect">
    <div style="border-bottom: 2px solid #eee">
      <el-upload @click.stop
        action="#" 
        :multiple="true"
        :show-file-list="false"
        :http-request="handleUpload"
        :before-upload="beforeUpload"
        :auto-upload="true"
      >
        <el-button
          class="upload-button" 
          style="width: 100%; height: 100%; background: transparent; padding: 0"
        >
          <div>本地上传</div>
        </el-button>
      </el-upload>
    </div>
    <div @click.stop="openSmartCaptureDialog">拍摄</div>
    <!-- 摄像头拍摄弹框 -->
    <el-dialog
      v-model="cameraDialogVisible"
      title="摄像头拍摄"
      width="60%"
      :show-close="true"
      :close-on-click-modal="false"
      class="camera-dialog"
    >
      <div class="camera-container">
        <!-- 摄像头预览区域 -->
        <div class="camera-preview">
          <video
            ref="videoElement"
            autoplay
            playsinline
            muted
            class="camera-video"
          ></video>

          <!-- 拍摄画布（用于捕获图片） -->
          <canvas
            ref="canvasElement"
            class="camera-canvas"
            style="display: none"
          ></canvas>
        </div>
      </div>

      <!-- 拍摄按钮 -->
      <template #footer>
        <div class="camera-footer">
          <el-button @click.stop="closeCameraDialog">取消</el-button>
          <el-button type="primary" @click.stop="capturePhoto" class="capture-btn">
            拍摄
          </el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 高拍仪拍摄弹框 -->
    <el-dialog
      v-model="scannerDialogVisible"
      title="高拍仪拍摄"
      width="60%"
      :show-close="true"
      :close-on-click-modal="false"
      class="scanner-dialog"
      @close="handleScannerDialogClose"
    >
      <div class="scanner-container"    element-loading-background="rgba(122, 122, 122, 0.8)" v-loading="!scannerVideoUrl" element-loading-text="高拍仪加载中...">
        <!-- 高拍仪预览区域 -->
        <div class="scanner-preview">
          <img
            v-if="scannerVideoUrl"
            :key="scannerVideoUrl"
            ref="scannerVideoElement"
            :src="scannerVideoUrl"
            alt="高拍仪预览"
            class="scanner-video"
          />
          <!-- <div v-if="!scannerVideoUrl" class="loading-overlay">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在连接高拍仪...</p>
          </div> -->
        </div>

        <!-- <div class="scanner-preview">
          <div  class="loading-overlay">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在连接高拍仪...</p>
          </div>
        </div> -->
      </div>

      <!-- 拍摄按钮 -->
      <template #footer>
        <div class="scanner-footer">
          <el-button @click="closeScannerDialog">取消</el-button>
          <el-button
            type="primary"
            @click="captureWithScannerDialog"
            :loading="scannerCapturing"
            class="capture-btn"
          >
            {{ scannerCapturing ? '拍摄中...' : '拍摄' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { uploadFile } from '@/api/basedata/index';
import { base64Upload } from '@/api/account';
import { getScannerInstance } from '@/utils/scanner';
import { Loading } from '@element-plus/icons-vue';

const emit = defineEmits(['updataBd', 'ps','updataBd2','loadingFalse']);
const cameraDialogVisible = ref(false);
interface ImageItem {
  url: string;
  file?: File;
  name: string;
}

const props = defineProps<{
  modelValue?: ImageItem[];
  fieldImages?: any;
  maxImages?: number;
  activeName_1?: string;
}>();
const loading = ref(false);
const mediaStream = ref<MediaStream | null>(null);
const videoElement = ref<HTMLVideoElement>();
const canvasElement = ref<HTMLCanvasElement>();

// 摄像头相关状态
const fileInput = ref<HTMLInputElement>();


// 高拍仪相关状态
const scannerDialogVisible = ref(false);
const scannerVideoElement = ref<HTMLImageElement>();
const scannerVideoUrl = ref('');
const scannerCapturing = ref(false);
const scannerConnectionStatus = ref<boolean | null>(null); // 缓存高拍仪连接状态

// 初始化高拍仪实例
const isHttpsEnv = typeof window !== 'undefined' && window.location.protocol === 'https:';
const scanner = getScannerInstance({ 
  // forceHttp: isHttpsEnv // HTTPS 环境下强制使用 HTTP，避免 WSS/HTTPS 连接问题
});

/**
 * 打开摄像头对话框（等待图像真正加载后再显示弹窗）
 */
const openCameraDialog = async () => {
  let tempVideo: HTMLVideoElement | null = null;
  
  try {
    emit('loadingFalse', true, '正在启动摄像头...');
    
    // 先获取摄像头权限和流
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user',
      },
    });
    
    mediaStream.value = stream;
    
    // 创建临时 video 元素来预加载视频流
    tempVideo = document.createElement('video');
    tempVideo.srcObject = stream;
    tempVideo.autoplay = true;
    tempVideo.muted = true;
    tempVideo.playsInline = true;
    
    // 等待视频流真正开始播放（图像加载完成）
    await new Promise<void>((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('摄像头加载超时'));
      }, 10000);
      
      if (tempVideo) {
        tempVideo.onloadeddata = () => {
          clearTimeout(timeout);
          resolve();
        };
        
        tempVideo.onerror = (error) => {
          clearTimeout(timeout);
          reject(error);
        };
      }
    });
    
    // 关闭加载提示
    emit('loadingFalse', false);
    
    // 图像加载完成后，打开对话框
    cameraDialogVisible.value = true;
    
    // 等待DOM更新后设置视频源
    await nextTick();
    if (videoElement.value) {
      videoElement.value.srcObject = stream;
    }
  } catch (error) {
    //console.error('无法访问摄像头:', error);
    
    // 清理资源
    if (mediaStream.value) {
      mediaStream.value.getTracks().forEach((track) => track.stop());
      mediaStream.value = null;
    }
    
    emit('loadingFalse', false);
    
    ElMessage({
      duration: 3000,
      message: '无法访问摄像头，请检查权限设置',
      type: 'error',
    });
  } finally {
    // 清理临时 video 元素
    if (tempVideo) {
      tempVideo.srcObject = null;
      tempVideo.remove();
      tempVideo = null;
    }
  }
};
/**
 * 智能拍摄对话框（优先高拍仪，无设备时使用电脑摄像头）
 */
const openSmartCaptureDialog = async () => {

  try {
    emit('loadingFalse', true, '设备启动中...');

    // 优先使用缓存的连接状态，如果没有则重新检测
    let isConnected = scannerConnectionStatus.value;
    
    if (isConnected === null) {
      // 首次检测
      isConnected = await scanner.checkConnection();
      scannerConnectionStatus.value = isConnected;
    }
    
    if (isConnected) {
      // 有高拍仪设备，打开预览
      try {
        await openScannerDialog();
      } catch (error: any) {
        //console.error('高拍仪启动失败，重新检测设备:', error);
        // 高拍仪启动失败，重新检测一次
        isConnected = await scanner.checkConnection();
        scannerConnectionStatus.value = isConnected;
        
        if (isConnected) {
          // 重试一次高拍仪
          try {
            await openScannerDialog();
          } catch (retryError: any) {
            //console.error('高拍仪重试失败，切换到摄像头:', retryError);
            // 重试失败，使用电脑摄像头
            ElMessage.warning('高拍仪连接失败，切换到电脑摄像头');
            await openCameraDialog();
          }
        } else {
          // 确认没有高拍仪，使用电脑摄像头
          await openCameraDialog();
        }
      }
    } else {
      // 没有高拍仪设备，使用电脑摄像头
      await openCameraDialog();
    }
  } catch (error: any) {
    //console.error('打开拍摄设备失败:', error);
    // 所有尝试失败，默认使用电脑摄像头
    ElMessage.warning('设备连接失败，尝试使用电脑摄像头');
    await openCameraDialog();
  }
};


// 拍摄照片
const capturePhoto = () => {
  if (!videoElement.value || !canvasElement.value) {
    ElMessage({
      message: '摄像头未准备就绪',
      type: 'error',
      duration: 2000,
    });
    return;
  }

  const video = videoElement.value;
  const canvas = canvasElement.value;
  const context = canvas.getContext('2d');

  if (!context) {
    ElMessage({
      message: '无法获取画布上下文',
      type: 'error',
      duration: 2000,
    });
    return;
  }

  // 设置画布尺寸与视频一致
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  // 绘制当前视频帧到画布
  context.drawImage(video, 0, 0, canvas.width, canvas.height);

  // 将画布内容转换为图片
  canvas.toBlob(
    (blob) => {
      if (!blob) {
        ElMessage({
          message: '拍摄失败',
          type: 'error',
          duration: 2000,
        });
        return;
      }

      const file = new File([blob], `capture_${Date.now()}.jpg`, {
        type: 'image/jpeg',
      });

      const reader = new FileReader();
      reader.onload = (e) => {
        const newImage: ImageItem = {
          url: e.target?.result as string,
          file: file,
          name: file.name,
        };
        scannerCapturing.value = true;
        uploadFile(file, file.name).then((res) => {
          if (mediaStream.value) {
            mediaStream.value.getTracks().forEach((track) => track.stop());
            mediaStream.value = null;
          }
          if (res.code == '200') {
            emit('updataBd2', res.data);
          }
          scannerCapturing.value = false;
          ElMessage({
            message: '上传成功',
            type: 'success',
            duration: 2000,
          });
          // 关闭拍摄弹框
          setTimeout(() => {
            closeCameraDialog();
          }, 300);
        });
      };
      reader.readAsDataURL(file);

     
    },
    'image/jpeg',
    0.9
  );
};
// 关闭拍摄弹框
const closeCameraDialog = () => {
  // 停止摄像头流
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => track.stop());
    mediaStream.value = null;
  }

  cameraDialogVisible.value = false;
};

const handleUpload = async (options: any) => {
  const { file } = options;
  //console.log(options);
  
  uploadFile(file, file.name).then((res) => {
    emit('updataBd', res.data);
  });
};

//文件上传
const beforeUpload = (file: any) => {
  // 验证文件类型
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) {
    //ElMessage.error('只能上传 JPG/PNG 格式的图片');
    return false;
  }
  return true;
};

/**
 * 打开高拍仪预览对话框（使用 WebSocket 视频流回调）
 */
const openScannerDialog = async () => {
  try {
    emit('loadingFalse', true, '设备启动中...');
    
    // 打开视频流，并设置回调函数
    const success = await scanner.openVideoStream(0, (base64: string) => {
      // 每次收到新帧时更新图片
      scannerVideoUrl.value = `data:image/jpeg;base64,${base64}`;
      
      // 首次收到图像时关闭加载提示并显示对话框
      if (!scannerDialogVisible.value) {
        emit('loadingFalse', false);
        scannerDialogVisible.value = true;
      }
    });

    if (!success) {
      throw new Error('无法打开高拍仪视频流');
    }
    
  } catch (error: any) {
    //console.error('打开高拍仪预览失败:', error);
    emit('loadingFalse', false);
    throw error;
  }
};
/**
 * 关闭高拍仪预览对话框
 */
const closeScannerDialog = async () => {
  try {
    // 关闭对话框
    scannerDialogVisible.value = false;
    
    // 重置状态
    scannerCapturing.value = false;
    
    // 清空视频URL
    scannerVideoUrl.value = '';
    
    // 关闭视频流并断开连接
    await scanner.closeVideoStream(0);
  } catch (error) {
    //console.error('关闭高拍仪预览失败:', error);
    // 即使关闭失败也要清空状态
    scannerVideoUrl.value = '';
    scannerCapturing.value = false;
    scannerDialogVisible.value = false;
  }
};

/**
 * 处理对话框关闭事件（包括点击X或ESC）
 */
const handleScannerDialogClose = async () => {
  // 关闭对话框
  scannerDialogVisible.value = false;
  
  // 重置状态
  scannerCapturing.value = false;
  
  // 清空视频URL
  scannerVideoUrl.value = '';
  
  // 关闭视频流并断开连接
  await scanner.closeVideoStream(0);
};
/**
 * 在对话框中使用高拍仪拍摄
 */
const captureWithScannerDialog = async () => {
  try {
    // 设置拍摄中状态
    scannerCapturing.value = true;

    // 调用高拍仪拍摄（视频流已打开，保持连接）
    const result = await scanner.capture(0, false, true);

    if (result.success && result.imageData) {
      // 处理Base64图片数据
      let base64Data = result.imageData;
      
      // 确保包含data:image前缀
      if (!base64Data.startsWith('data:image')) {
        base64Data = `data:image/jpeg;base64,${base64Data}`;
      }

      // 上传到服务器
      const uploadResult = await base64Upload({
        baseStr: base64Data,
        isCompress: 'true',
      });
      
      if (uploadResult.code === '200' && uploadResult.data) {
        //console.log('✅ 高拍仪拍摄成功');
        //console.log('📤 准备 emit updataBd2，数据:', uploadResult.data);
        
        // 立即 emit 给父组件，让父组件处理数据和关闭逻辑
        emit('updataBd2', uploadResult.data); 
        
        //console.log('✅ emit updataBd2 已调用');
        
        ElMessage.success('高拍仪拍摄成功');
        
        // 关闭对话框，但不隐藏组件（由父组件控制）
        closeScannerDialog();
      } else {
        //console.error('❌ 图片上传失败');
        //console.error('上传结果:', uploadResult);
        ElMessage.error(uploadResult.msg || '图片上传失败');
      }
    } else {
      //console.error('高拍仪拍摄失败:', result.error);
      ElMessage.error(result.error || '高拍仪拍摄失败');
    }
  } catch (error: any) {
    //console.error('高拍仪拍摄异常:', error);
    ElMessage.error(error.message || '高拍仪拍摄失败');
  } finally {
    // 恢复按钮状态
    scannerCapturing.value = false;
  }
};

/**
 * 初始化检测高拍仪连接状态（静默检测，不影响用户体验）
 */
const initScannerDetection = async () => {
  try {
    const isConnected = await scanner.checkConnection();
    scannerConnectionStatus.value = isConnected;
    
    // 仅在开发环境输出调试信息
    if (import.meta.env.DEV) {
      //console.log('[UpdataSelect] 高拍仪设备状态:', isConnected ? '已连接' : '未连接');
    }
  } catch (error: any) {
    //console.error('[UpdataSelect] 检测高拍仪连接失败:', error);
    scannerConnectionStatus.value = false;
  }
};

// 组件挂载时初始化
onMounted(() => {
  // 异步检测高拍仪连接状态，不阻塞页面加载
  initScannerDetection();
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => track.stop());
  }
});
</script>
<style scoped lang="scss">
.updataSelect {
  :deep(.el-button.upload-button) {
    background: transparent;
    border: none;
  }
  position: absolute;
  width: 150px;
  left: 57px;
  top: 73px;
  z-index: 1000;
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 12px 32px 0px rgba(0, 0, 0, 0.2);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #d9d9d9;
  > div {
    font-size: 14px;
    color: #434343;
    line-height: 38px;
    cursor: pointer;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}

// 摄像头拍摄弹框样式
.camera-dialog {
  .camera-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: #f5f5f5;
    border-radius: 8px;
  }

  .camera-preview {
    position: relative;
    width: 100%;
    max-width: 800px;
    background: #000;
    border-radius: 8px;
    overflow: hidden;
  }

  .camera-video {
    width: 100%;
    height: auto;
    display: block;
  }

  .camera-canvas {
    position: absolute;
    top: 0;
    left: 0;
  }

  .camera-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding: 16px 0;

    .capture-btn {
      padding: 12px 32px;
      font-size: 16px;
      background: #16ada4;
      border-color: #16ada4;

      &:hover {
        background: #139a92;
        border-color: #139a92;
      }
    }
  }
}

// 下拉菜单样式
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    font-size: 16px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .image-display-area {
    flex-direction: column;
  }

  .image-item {
    width: 100px;
    height: 100px;
  }

  .camera-dialog,
  .scanner-dialog {
    .camera-footer,
    .scanner-footer {
      flex-direction: column;
      align-items: center;

      .el-button {
        width: 120px;
      }
    }
  }
}

// 高拍仪拍摄弹框样式
.scanner-dialog {
  .scanner-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: #f5f5f5;
    border-radius: 8px;
  }

  .scanner-preview {
    position: relative;
    width: 100%;
    max-width: 800px;
    background: #000;
    border-radius: 8px;
    overflow: hidden;
    min-height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .scanner-video {
    width: 100%;
    height: auto;
    display: block;
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    
    .el-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    p {
      font-size: 16px;
      margin: 0;
    }
  }

  .scanner-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding: 16px 0;

    .capture-btn {
      padding: 12px 32px;
      font-size: 16px;
      background: #16ada4;
      border-color: #16ada4;

      &:hover {
        background: #139a92;
        border-color: #139a92;
      }
      
      &:disabled,
      &.is-loading {
        background: #a0cfff;
        border-color: #a0cfff;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .camera-dialog,
  .scanner-dialog {
    .camera-footer,
    .scanner-footer {
      flex-direction: column;
      align-items: center;

      .el-button {
        width: 120px;
      }
    }
  }
}
</style>
